<template>
  <el-tabs class="userTemp" v-model="activeName">
    <el-button v-waves @click="addNew" style="float: right;margin: 15px;" type="primary" size="small">新建账户</el-button>
    <el-tab-pane label="主管账号" name="first">
      <el-table empty-text="暂无任何用户信息" :row-class-name="rowClassName" :data="list" v-loading.body="listLoading" border fit  style="width: 100%">
        <el-table-column align="center" label="所属公司">
          <template slot-scope="scope">
            <span>{{!!scope.row.companyName ? scope.row.companyName : '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户姓名" >
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="行业">
          <template slot-scope="scope">
            <span>{{scope.row.industryName}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户邮箱">
          <template slot-scope="scope">
            <span>{{!!scope.row.email ? scope.row.email : '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户手机号">
          <template slot-scope="scope">
            <span>{{scope.row.phone}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="账号角色">
          <template slot-scope="scope">
            <span>{{ scope.row.roleId | roleMap(scope.row.roleId) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关键信息开关">
          <template slot-scope="scope" >
            <el-switch
              v-model="scope.row.switch"
              @change="switchChange(scope.row)"
              :active-value="1"
              :inactive-value="2"
              active-color="#409eff"
              inactive-color="#ccc"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="320">
          <template slot-scope="scope">
            <el-button v-waves @click="openEvent(scope.row,scope.$index)"  type="warning"  size="small" icon="el-icon-circle-close-outline">{{ scope.row.enable === 1 ? '锁定' : '解锁' }}</el-button>
            <el-button v-if="scope.row.enable === 1" v-waves @click="editUser(scope.row)"  type="success"  size="small" icon="el-icon-edit">编辑</el-button>
            <router-link @click.native="saveUser(scope.row)" style="margin-left: 8px;" :to="{path:'/user/details',query:{id:scope.row.userId}}">
              <el-button type="primary" size="small" icon="el-icon-document">
                详情
              </el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange" :current-page.sync="listQuery.current"
                       :page-sizes="[10,20,30,50]" :page-size="listQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-tab-pane>
    <el-tab-pane label="内部账号" name="second">
    </el-tab-pane>
    <el-tab-pane label="机构账号" name="third">
    </el-tab-pane>

    <el-table v-if="activeName != 'first'" empty-text="暂无任何用户信息" :row-class-name="rowClassName" :data="inList" v-loading.body="inListLoading" border fit style="width: 100%">

      <el-table-column align="center" label="用户姓名" >
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="activeName == 'third'" align="center" label="行业">
        <template slot-scope="scope">
          <span>{{!!scope.row.industryName ? scope.row.industryName : '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户邮箱">
        <template slot-scope="scope">
          <span>{{!!scope.row.email ? scope.row.email : '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"  label="用户手机号">
        <template slot-scope="scope">
          <span>{{ !!scope.row.phone ? scope.row.phone : '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号角色">
        <template slot-scope="scope">
          <span>{{ scope.row.roleId | roleMap(scope.row.roleId) }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="320">
        <template slot-scope="scope">
          <el-button v-waves @click="openEvent(scope.row,scope.$index)"  type="warning"  size="small" icon="el-icon-circle-close-outline">{{ scope.row.enable === 1 ? '锁定' : '解锁' }}</el-button>
          <el-button v-waves v-if="scope.row.enable === 1"  @click="openDialog(scope.row)"  type="success"  size="small" icon="el-icon-edit">编辑</el-button>
        </template>
      </el-table-column>

    </el-table>
    <div v-show="!inListLoading && activeName != 'first'" class="pagination-container">
      <el-pagination background @size-change="inHandleSizeChange" prev-text="上一页" next-text="下一页" @current-change="inHandleCurrentChange" :current-page.sync="inListQuery.current"
                     :page-sizes="[10,20,30,50]" :page-size="inListQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="inTotal">
      </el-pagination>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      @open="setCurrentDialogText"
      @click="dialogVisible = false"
    >
      <el-alert
        :title="currentText"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="() => activeName == 'third' ? enableOrg() : enableEvent()">确 定</el-button>
      </span>
    </el-dialog>

    <keep-alive>
      <el-dialog @close="cancledialog('userForm')" top="60px"  width="400px" :title="titleText" :visible.sync="infoFormVisible">
        <el-form :model="updateInfo" :rules="userEditRules" ref="userForm">
          <el-form-item label="用户名" prop="name" :label-width="formLabelWidth">
            <el-input v-model.sync.trim="updateInfo.name"  auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="activeName === 'first' && isAdd "  label="公司名" prop="companyName" :label-width="formLabelWidth">
            <el-input v-model.sync.trim="updateInfo.companyName"  auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="activeName != 'second'" prop="industryId" label="行业" :label-width="formLabelWidth">
            <el-select v-model="updateInfo.industryId" placeholder="请选择">
              <el-option
                v-for="item in industry"
                :key="item.industryId"
                :label="item.industryName"
                :value="item.industryId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="activeName == 'second'" label="账户类型" prop="roleId" :label-width="formLabelWidth">
            <el-radio-group v-model="updateInfo.roleId">
              <el-radio :label.number="2">运营</el-radio>
              <el-radio :label.number="1">管理员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input  v-model.trim="updateInfo.email" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone" :label-width="formLabelWidth">
            <el-input  v-model.trim="updateInfo.phone" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="activeName == 'first'" label="账户类型" prop="roleId" :label-width="formLabelWidth">
            <el-radio-group v-model="updateInfo.roleId">
              <el-radio :label.number="3">内部主管</el-radio>
              <el-radio :label.number="5">第三方主管</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
            <el-input  v-model.trim="updateInfo.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkNewPwd" :label-width="formLabelWidth">
            <el-input  v-model.trim="updateInfo.checkNewPwd" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="infoFormVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="() => activeName == 'third' ? updateOrg() : update()">确 定</el-button>
        </div>
      </el-dialog>
    </keep-alive>
  </el-tabs>
</template>
<script>
import {
  getInsideList,
  getAdvertiserList,
  getIndustryList,
  editUser,
  addUser,
  enableSwitch,
  enableUser,
  getOrgannList, // 获取机构列表
  addEditOrgan, //添加编辑机构账号
  enableOrg //锁定/解锁机构
} from "@/api/user";
import waves from "@/directive/waves"; // 水波纹指令

import { getRanNum, base64encode } from "@/utils/index";

export default {
  name: "user-comp",
  directives: {
    waves
  },
  data() {
    const checkNewPwd = (rule, value, callback) => {
      console.log("rule", rule);
      console.log("value", value);
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.updateInfo.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    const CheckTel = (rule, value, callback) => {
      let tempValue = value * 1;
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!Number.isInteger(tempValue)) {
        callback(new Error("电话号码必须是数字"));
      } else if (value.toString().length != 11) {
        callback(new Error("电话号码必须是11位"));
      } else {
        callback();
      }
    };

    const userEditRules = {
      name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      companyName: [
        { required: true, message: "请输入公司名", trigger: "blur" },
        { max: 16, message: "用户名长度不能大于50位", trigger: "blur" }
      ],
      industryId: [
        {
          required: true,
          type: "number",
          message: "请选择行业",
          trigger: "change"
        }
      ],
      email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      phone: [{ required: true, validator: CheckTel, trigger: "blur" }],
      password: [
        { message: "请输入密码", trigger: "blur" },
        { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
        { max: 16, message: "密码长度不能大于16位", trigger: "blur" }
      ],
      roleId: [
        { required: true, message: "请选择账户类型", trigger: "change" }
      ],
      checkNewPwd: [{ validator: checkNewPwd, trigger: "blur" }]
    };
    return {
      currentItem: null,
      currentIndex: null,
      dialogVisible: false,
      currentText: "",
      industry: [],
      activeName: "first",
      isAdd: false,
      infoFormVisible: false,
      updateInfo: {},
      formLabelWidth: "120px",
      userEditRules: userEditRules,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        pagesize: 10
      },
      inList: [],
      inTotal: 0,
      inListLoading: true,
      inListQuery: {
        current: 1,
        pagesize: 10,
        userId: null
      }
    };
  },
  created() {
    //先把当前内部账号的userId 传给后台
    this.inListQuery.userId = this.$store.getters.updateInfo.userId;
    this.getList();
    this.getInList();
    this.getIndustryList();
  },
  watch: {
    activeName(val) {
      if (val != "first") {
        this.inListQuery.pagesize = 10;
        this.inListQuery.current = 1;
        this.getInList();
      }
    }
  },
  computed: {
    titleText() {
      let text = this.isAdd ? "添加" : "编辑";
      text +=
        this.activeName === "first"
          ? "数据主管账号"
          : this.activeName === "second" ? "内部账号" : "机构账号";
      return text;
    }
  },
  methods: {
    switchChange(item) {
      //改变后的值
      enableSwitch({ companyId: item.companyId, enable: item.switch * 1 })
        .then(res => {
          this.$message.success("设置成功");
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    openDialog(items) {
      this.infoFormVisible = true;
      this.updateInfo = Object.assign({}, this.updateInfo, items);
    },
    getIndustryList() {
      getIndustryList()
        .then(res => {
          let info = res.data.info;
          this.industry = info;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    getList() {
      this.listLoading = true;
      getAdvertiserList(this.listQuery)
        .then(response => {
          const temp = response.data;
          this.total = temp.total;
          this.list = temp.userInfo;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
          this.$message.error(res);
        });
    },
    getInList() {
      let tempFunc =
        this.activeName == "second" ? getInsideList : getOrgannList;
      this.inListLoading = true;
      tempFunc(this.inListQuery)
        .then(response => {
          const temp = response.data;
          this.inTotal = temp.total;
          this.inList = temp.userInfo;
          this.inListLoading = false;
        })
        .catch(res => {
          this.inListLoading = false;
          this.$message.error(res);
        });
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    inHandleSizeChange(val) {
      this.inListQuery.pagesize = val;
      this.getInList();
    },
    inHandleCurrentChange(val) {
      this.inListQuery.current = val;
      this.getInList();
    },
    cancledialog(userForm) {
      //重置表单
      this.$refs[userForm].resetFields();
      this.updateInfo = {};
      this.isAdd = false;
    },
    editUser(item) {
      this.updateInfo = Object.assign({}, this.updateInfo, item);
      this.infoFormVisible = true;
    },
    addNew() {
      this.isAdd = true;
      this.infoFormVisible = true;
    },
    setCurrentDialogText() {
      let text = this.currentItem.enable === 1 ? "锁定" : "解锁";
      this.currentText = "您确认要" + text + "该账号 ?";
    },
    enableOrg() {
      if (!this.currentItem) return;
      let thisEnable = this.currentItem.enable === 1 ? 2 : 1;
      let thisOrgId = this.currentItem.orgId;
      let tempText = thisEnable === 2 ? "锁定" : "解锁";
      enableOrg({ orgId: thisOrgId, enable: thisEnable })
        .then(res => {
          this.inList[this.currentIndex].enable = thisEnable;
          this.dialogVisible = false;
          this.$message.success(tempText + "成功");
        })
        .catch(res => {
          this.dialogVisible = false;
          this.$message.success(tempText + "失败 " + res);
        });
    },
    enableEvent() {
      if (!this.currentItem) return;
      let thisEnable = this.currentItem.enable === 1 ? 2 : 1;
      let isInside = this.activeName === "first" ? false : true;
      let thisUserId = this.currentItem.userId;
      let tempList = this.activeName === "first" ? this.list : this.inList;
      let tempText = thisEnable === 2 ? "锁定" : "解锁";
      enableUser({ userId: thisUserId, enable: thisEnable }, isInside)
        .then(res => {
          tempList[this.currentIndex].enable = thisEnable;
          this.dialogVisible = false;
          this.$message.success(tempText + "成功");
        })
        .catch(res => {
          this.dialogVisible = false;
          this.$message.success(tempText + "失败 " + res);
        });
    },
    openEvent(val, index) {
      this.dialogVisible = true;
      this.currentItem = val;
      this.currentIndex = index;
    },
    rowClassName({ row, rowIndex }) {
      if (row.enable === 2) {
        return "warning-row";
      }
      return "";
    },
    updateOrg() {
      this.$refs["userForm"].validate(valid => {
        if (!valid) {
          this.$message.error("修改失败,请确认您的信息后再提交");
          return;
        }
        var tempData = Object.assign({}, this.updateInfo);
        delete tempData.checkNewPwd;
        if (!!tempData.password) {
          tempData.password =
            getRanNum(8) + base64encode(tempData.password) + getRanNum(8);
        }
        addEditOrgan(tempData, this.isAdd)
          .then(res => {
            this.$message.success(this.isAdd ? "添加成功" : "修改成功");
            this.getInList();
            this.infoFormVisible = false;
          })
          .catch(res => {
            this.$message.error(res);
          });
      });
    },
    update() {
      let isInside = this.activeName === "first" ? false : true;
      let tempFunc = this.isAdd ? addUser : editUser;
      // this.activeName === 'first' ? this.updateInfo.roleId = 3 : null;

      this.$refs["userForm"].validate(valid => {
        if (!valid) {
          this.$message.error("修改失败,请确认您的信息后再提交");
          return;
        }
        var tempData = Object.assign({}, this.updateInfo);
        delete tempData.checkNewPwd;
        if (!!tempData.password) {
          tempData.password =
            getRanNum(8) + base64encode(tempData.password) + getRanNum(8);
        }
        tempData.switch = tempData.switch * 1;
        tempFunc(tempData, isInside)
          .then(res => {
            this.$message.success(this.isAdd ? "添加成功" : "修改成功");
            this.activeName === "first" ? this.getList() : this.getInList();
            this.infoFormVisible = false;
          })
          .catch(res => {
            this.$message.error(res);
          });
      });
    },
    saveUser(item) {
      let local_user = localStorage.getItem("AD_USER");
      !!local_user ? localStorage.removeItem("AD_USER") : null;
      localStorage.setItem("AD_USER", JSON.stringify(item));
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
.userTemp {
  .el-alert--warning {
    background-color: #fff;
  }
}
</style>
